package org.vy.dal;


public class DALCtx {
	
	private DBConnection con = null;
	
	private static ThreadLocal<DALCtx> dalCtx = new ThreadLocal<DALCtx>() {
        protected synchronized DALCtx initialValue() {
        	DALCtx dCtx = new DALCtx();
        	try{
        		dCtx.setCon(ConnectionManager.getInstance().getConnection());
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        	return dCtx;
        }
    };
 
    public static DALCtx ctx(){
    	return dalCtx.get();
    }

	DBConnection getCon() {
		return con;
	}

	private void setCon(DBConnection con) {
		this.con = con;
	}
    
	public void beginTransaction() {
		con.setAutoCommit(false);
	}
	
	public void commitTransaction() {
		con.commit();
		con.setAutoCommit(true);
	}

	public void rollbackTransaction() {
		con.rollback();
		con.setAutoCommit(true);
	}

	public void finalize(){
		try{
			if(con != null){
				con.commit();
				ConnectionManager.getInstance().freeConnection(con);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

